package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.controller.websocket.WebSocketServer;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PutMapping;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImol implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 用户下单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Transactional
    @Override
    public OrderSubmitVO PlaceOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //判断地址薄是不是空
        AddressBook byId = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (byId == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //判断购物车为不为空
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(BaseContext.getCurrentId());
        List<ShoppingCart> shoppingCart1 = shoppingCartMapper.getShoppingCart(shoppingCart);
        if (shoppingCart1 == null || shoppingCart1.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        String provinceName = byId.getProvinceName();
        String cityName = byId.getCityName();
        String districtName = byId.getDistrictName();
        String detail = byId.getDetail();
        String s = provinceName + cityName + districtName + detail;
        //向订单表插入
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setUserId(shoppingCart.getUserId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setPhone(byId.getPhone());
        orders.setConsignee(byId.getConsignee());
        orders.setAddress(s);
        orderMapper.put(orders);

        //向订单明细表插入
        OrderDetail orderDetail = new OrderDetail();
        for (ShoppingCart cart : shoppingCart1) {
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailMapper.put(orderDetail);
        }

        //插入之后清空购物车
        shoppingCartMapper.delete(shoppingCart);

        //返回VO对象
        OrderSubmitVO build = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
        return build;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        Map map = new HashMap();
        map.put("type", 1);//消息类型，1表示来单提醒
        map.put("orderId", orders.getId());
        map.put("content", "订单号：" + outTradeNo);

        //通过WebSocket实现来单提醒，向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    /**
     * 历史订单查询
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageGetOrder(OrdersPageQueryDTO ordersPageQueryDTO) {
        //先设置分页查询参数
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        //将线程空间的用户ID设置进来
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        //根据用户ID和前端传进来的状态进行查询并设置返回值为Page，泛型用订单表的实体类来接收
        Page<Orders> orders = orderMapper.getUserId(ordersPageQueryDTO);

        //new一个新集合并且将泛型设置为VO类型最后用于返回
        List<OrderVO> orderVO = new ArrayList<>();
        //遍历返回的订单表集合
        for (Orders order : orders) {
            //获取每个订单表的ID
            Long id = order.getId();
            //根据订单ID查找订单明细表
            List<OrderDetail> orderDetail = orderDetailMapper.getId(id);
            OrderVO VO = new OrderVO();
            //拷贝每个订单表数据到VO对象
            BeanUtils.copyProperties(order, VO);
            //设置VO的OrderDetailList为订单明细表的返回值
            VO.setOrderDetailList(orderDetail);
            orderVO.add(VO);
        }
        return new PageResult(orders.getTotal(), orderVO);
    }

    /**
     * 查询订单详情
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO getOrderId(Long id) {
        Orders o = orderMapper.getOrderId(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(o, orderVO);
        if (o != null) {
            List<OrderDetail> orderDetails = orderDetailMapper.getId(id);
            orderVO.setOrderDetailList(orderDetails);
        }
        return orderVO;
    }

    /**
     * 取消订单
     *
     * @param id
     */
    @Override
    public void cancelOrder(Long id) {
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 再来一单
     *
     * @param id
     */
    @Override
    public void againOrder(Long id) {
        //根据传入的订单ID查找所有的订单详细表
        List<OrderDetail> orderDetails = orderDetailMapper.getId(id);
        //遍历每个订单详细表
        for (OrderDetail orderDetail : orderDetails) {
            ShoppingCart shoppingCart1 = new ShoppingCart();
            //设置用户ID为线程空间此时操作的用户
            shoppingCart1.setUserId(BaseContext.getCurrentId());
            //设置操作时间
            shoppingCart1.setCreateTime(LocalDateTime.now());
            //因为订单明细表与购物车字段相差不多，所以直接拷贝
            BeanUtils.copyProperties(orderDetail, shoppingCart1);
            shoppingCartMapper.insert(shoppingCart1);
        }
    }

    /**
     * 订单搜索
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult orderSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> orders = orderMapper.getUserId(ordersPageQueryDTO);


        List<OrderVO> orderVO = new ArrayList<>();
        //遍历返回的订单表集合


        for (Orders order : orders) {
            //获取每个订单表的ID
            Long id = order.getId();
            //根据订单ID查找订单明细表
            List<OrderDetail> orderDetail = orderDetailMapper.getId(id);
            //调用方法来拼接菜品信息
            String name = getdish(orderDetail);
            OrderVO VO = new OrderVO();
            //拷贝每个订单表数据到VO对象
            BeanUtils.copyProperties(order, VO);
            //设置VO的OrderDetailList为订单明细表的返回值
            VO.setOrderDetailList(orderDetail);
            VO.setOrderDishes(name);
            orderVO.add(VO);
        }
//        if (orders.getTotal() < 1){
//            throw new AccountLockedException(MessageConstant.ORDER_NOT_FOUND);
//        }
        return new PageResult(orders.getTotal(), orderVO);
    }

    /**
     * 订单搜索内容的菜品信息拼接（被订单搜索调用）
     * @param orderDetail
     * @return
     */
    private String getdish(List<OrderDetail> orderDetail) {
        String name1 = "";
        for (OrderDetail detail : orderDetail) {
            String name = detail.getName();
            Integer number = detail.getNumber();
            name1 = name + "*" + number + ";" + name1;
        }
        return name1;
    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void declines(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orders = orderMapper.getOrderId(ordersRejectionDTO.getId());
        if (orders == null || !orders.getStatus().equals(Orders.TO_BE_CONFIRMED) || !orders.getPayStatus().equals(Orders.PAID)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setPayStatus(Orders.REFUND);
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void Cancel(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = orderMapper.getOrderId(ordersCancelDTO.getId());
        if (orders.getStatus().equals(Orders.CONFIRMED) || orders.getStatus().equals(Orders.DELIVERY_IN_PROGRESS) ||
                orders.getStatus().equals(Orders.COMPLETED)){
            orders.setStatus(Orders.CANCELLED);
            BeanUtils.copyProperties(ordersCancelDTO,orders);
            orders.setCancelTime(LocalDateTime.now());
            orderMapper.update(orders);
        }
    }

    /**
     * 派送订单
     * @param id
     */
    @Override
    public void delivery(Long id) {
        Orders orders = orderMapper.getOrderId(id);
        if (orders == null || !orders.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
            Orders or = new Orders();
            or.setId(orders.getId());
            or.setStatus(Orders.DELIVERY_IN_PROGRESS);
            orderMapper.update(or);
    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void complete(Long id) {
        Orders orderId = orderMapper.getOrderId(id);
        if (orderId.getStatus() == Orders.DELIVERY_IN_PROGRESS){
            Orders orders = new Orders();
            orders.setId(id);
            orders.setStatus(Orders.COMPLETED);
            orders.setDeliveryTime(LocalDateTime.now());
            orderMapper.update(orders);
        }
    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO details(Long id) {
        Orders orderId = orderMapper.getOrderId(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orderId,orderVO);
        List<OrderDetail> list = orderDetailMapper.getId(id);
        orderVO.setOrderDetailList(list);
        return orderVO;
    }

    /**
     * 根据状态统计
     * @return
     */
    @Override
    @Transactional
    public OrderStatisticsVO statistics() {
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        Integer toBeConfirmed = orderMapper.statistics(Orders.TO_BE_CONFIRMED);
        Integer confirmed = orderMapper.statistics(Orders.CONFIRMED);
        Integer deliveryInProgress = orderMapper.statistics(Orders.DELIVERY_IN_PROGRESS);

        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }

    /**
     * 接单
     * @param
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orderId = orderMapper.getOrderId(ordersConfirmDTO.getId());
        if (!orderId.getStatus().equals(Orders.TO_BE_CONFIRMED) || !orderId.getPayStatus().equals(Orders.PAID)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        orderId.setId(ordersConfirmDTO.getId());
        orderId.setStatus(Orders.CONFIRMED);
        orderMapper.update(orderId);
    }

    /**
     * 催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
        Orders orderId = orderMapper.getOrderId(id);
        if (orderId == null){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Map map = new HashMap();
        map.put("type",2);
        map.put("orderId",id);
        map.put("content","订单号"+orderId.getNumber());

        //通过webSocketServer向浏览器客户端推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }
}
